<template>
  <div flex>
    <div bd-fff mr-10px w="[30%]">
      <div pt-24px pb-24px pl-35px pr-25px>
        <el-input v-model="filterText" placeholder="输入搜索关键词">
          <template #append>
            <el-button icon="search" />
          </template>
        </el-input>
      </div>
      <!-- @vue-ignore -->
      <el-tree
        ref="treeRef"
        pt-10px
        pb-10px
        pl-10px
        pr-15px
        :icon="ArrowRightBold"
        :data="dataSource"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
      >
        <template #default="{ node, data }">
          <div flex-1 flex items-center justify-between>
            <div color-000 flex items-center>
              <el-icon v-if="data.id === 1" mr-8px><Folder /></el-icon>
              <el-icon v-else mr-8px><Document /></el-icon>
              <div>{{ node.label }}</div>
            </div>
            <div>
              <el-icon @click="append(data)"><Plus /></el-icon>
              <el-icon ml-12px mr-12px @click="append(data)"><EditPen /></el-icon>
              <el-icon @click="remove(node, data)"><Delete /></el-icon>
            </div>
          </div>
        </template>
      </el-tree>
    </div>
    <div overflow-hidden>
      <div h-75px bd-fff pt-30px pl-20px pr-20px mb-10px flex justify-between items-center>
        <div>
          <el-button
            plain
            text-15px
            type="primary"
            style="
              font-size: 15px;
              color: #fff;
              background: linear-gradient(
                90deg,
                rgba(0, 108, 222, 1) 0%,
                rgba(41, 182, 244, 1) 100%,
                rgba(0, 163, 235, 1) 99%
              );
              border: none;
            "
            @click="handleOpen"
          >
            新增机构
          </el-button>
          <el-button
            plain
            text-15px
            style="color: rgba(0, 108, 222, 1); border: 1px solid rgba(0, 108, 222, 1)"
          >
            转移
          </el-button>
        </div>
        <div flex items-center>
          <div mr--10px>
            <el-input v-model="input3" placeholder="请输入内容">
              <template #prepend>
                <el-select v-model="select" placeholder="请选择" style="width: 115px">
                  <el-option label="Restaurant" value="1" />
                  <el-option label="Order No." value="2" />
                  <el-option label="Tel" value="3" />
                </el-select>
              </template>
            </el-input>
          </div>
          <el-button type="primary" text-15px z-2 icon="search">搜索</el-button>
          <el-button
            plain
            text-15px
            :icon="RefreshRight"
            style="color: rgba(0, 108, 222, 1); border: 1px solid rgba(0, 108, 222, 1)"
          >
            清空
          </el-button>
          <el-dropdown ml-10px trigger="click">
            <el-button
              plain
              text-15px
              :icon="Grid"
              style="color: rgba(0, 108, 222, 1); border: 1px solid rgba(0, 108, 222, 1)"
            >
              更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu style="color: #2778ff">
                <el-dropdown-item :icon="DocumentCopy" @click="dropdownItemClick('copy')">
                  复制
                </el-dropdown-item>
                <el-dropdown-item :icon="Printer" @click="dropdownItemClick('printer')">
                  打印
                </el-dropdown-item>
                <el-dropdown-item :icon="Expand" @click="dropdownItemClick('export')">
                  导出
                </el-dropdown-item>
                <el-dropdown-item :icon="Checked" @click="dropdownItemClick('archive')">
                  归档
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <PlusTable
        key="3"
        :is-selection="true"
        adaptive
        has-index-column
        :title-bar="false"
        :header-cell-style="{
          backgroundColor: '#F1F3F7',
          color: '#000',
        }"
        :index-table-column-props="{
          label: '序号',
          width: 80,
        }"
        :columns="tableConfig"
        :table-data="tableData"
        :stripe="true"
        :border="false"
        :action-bar="{
          buttons: buttons2,
          type: 'link',
          confirmType: 'popconfirm',
          width: 200,
        }"
        :pagination="{
          total,
          modelValue: pageInfo,
          pageSizeList: [10, 20, 50],
          background: true,
          align: 'right',
        }"
        @paginationChange="handlePaginationChange"
        @selection-change="handleSelectionChange"
        @clickAction="handleClickButton"
      ></PlusTable>
      <!-- 弹窗表单 -->
      <PlusDialogForm
        v-model:visible="visible"
        v-model="values"
        :show-close="false"
        :form="{ columns, rules, labelWidth: '95px', rowProps: { gutter: 40 } }"
        :dialog="{ title: '添加/编辑组织机构', width: '900px', confirmLoading }"
        @confirm="handleSubmit"
      >
        <template #dialog-footer>
          <div pt-30px pb-40px style="margin: 0 auto">
            <el-button
              plain
              text-14px
              w-98px
              type="primary"
              style="
                font-size: 15px;
                color: #fff;
                background: linear-gradient(
                  90deg,
                  rgba(0, 108, 222, 1) 0%,
                  rgba(41, 182, 244, 1) 100%,
                  rgba(0, 163, 235, 1) 99%
                );
                border: none;
              "
              @click="handleSubmit"
            >
              提交
            </el-button>
            <el-button w-98px style="margin-left: 55px !important" plain @click="handleCancel">
              取消
            </el-button>
          </div>
        </template>
      </PlusDialogForm>
      <!-- 确认弹窗 -->
      <PlusDialog
        v-model="show"
        class="small-dialog"
        title="确认信息"
        @confirm="handleSmallConfirm"
      >
        确认删除此行数据吗？
        <template #footer>
          <div pt-44px pb-43px style="margin: 0 auto">
            <el-button
              plain
              text-14px
              w-98px
              type="primary"
              style="
                font-size: 15px;
                color: #fff;
                background: linear-gradient(
                  90deg,
                  rgba(0, 108, 222, 1) 0%,
                  rgba(41, 182, 244, 1) 100%,
                  rgba(0, 163, 235, 1) 99%
                );
                border: none;
              "
            >
              提交
            </el-button>
            <el-button w-98px style="margin-left: 55px !important" plain @click="handleSmallCancel">
              取消
            </el-button>
          </div>
        </template>
      </PlusDialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useTable } from "plus-pro-components";
import type { PlusColumn, ButtonsCallBackParams, PageInfo, FieldValues } from "plus-pro-components";
import type { TreeInstance } from "element-plus";
import type Node from "element-plus/es/components/tree/src/model/node";
import {
  View,
  RefreshRight,
  Grid,
  DocumentCopy,
  Printer,
  Expand,
  Checked,
  ArrowRightBold,
} from "@element-plus/icons-vue";

interface TableRow {
  id: number;
  name: string;
  status: string;
  tag: string;
  time: Date;
}

const input3 = ref("");
const select = ref("");

const multipleSelection = ref<TableRow[]>([]);
// start table
const TestServe = {
  getList: async () => {
    const data = Array.from({ length: 10 }).map((item, index) => {
      return {
        id: index,
        name: index + "深邦智能科技集团",
        person: "中国",
        code: "山东 青岛 城阳区",
        money: 1000 + index + "万元",
        time: new Date(),
        address: `天谷产业园${index}号楼`,
        type: "总部",
        status: String(index % 3),
        tag: index === 1 ? "success" : index === 2 ? "warning" : index === 3 ? "info" : "danger",
      };
    });
    return {
      data: data as TableRow[],
    };
  },
};

const { buttons: buttons2, tableData, total, pageInfo } = useTable<TableRow[]>();

buttons2.value = [
  {
    // 打开
    text: "编辑",
    code: "edit",
    props: {
      type: "primary",
    },
    // confirm: {
    //   // @ts-ignore
    //   popconfirmProps: { width: 150, icon: WarnTriangleFilled, iconColor: "red" },
    //   message: (data) => `确定打开id为${data.row.id}的数据吗？`,
    // },
  },
  {
    // 查看
    text: "详情",
    code: "view",
    icon: View,
    props: {
      type: "primary",
    },
    // show: (row: any) => row.status === "1",
  },
  {
    // 删除
    text: "删除",
    code: "delete",
    // props v0.1.16 版本新增计算属性支持
    props: computed(() => ({ type: "primary" })),
    // confirm: {
    //   // @ts-ignore
    //   popconfirmProps: { width: 200, icon: WarnTriangleFilled, iconColor: "red" },
    //   message: (data) => `确定删除id为${data.row.id}且行数为${data.index}的数据吗？`,
    // },
  },
];

const tableConfig: PlusColumn[] = [
  {
    label: "组织名称",
    prop: "name",
    width: 200,
    tableColumnProps: {
      // showOverflowTooltip: true,
      fixed: "left",
    },
  },
  {
    label: "上级组织",
    prop: "person",
  },
  {
    label: "组织级别",
    width: 200,
    prop: "code",
  },
  {
    label: "组织编码",
    width: 200,
    prop: "address",
  },
  {
    label: "组织层级",
    prop: "type",
  },
  {
    label: "部门负责人",
    width: 100,
    prop: "type",
  },
  {
    label: "上级负责人",
    width: 100,
    prop: "type",
  },
  {
    label: "编制人数",
    prop: "type",
  },
  {
    label: "在编人数",
    prop: "type",
  },
  {
    label: "状态",
    prop: "type",
  },
];

const getList = async () => {
  try {
    const { data } = await TestServe.getList();
    tableData.value = data || [];
  } catch (error) {
    console.error("获取数据失败", error);
  }
};
getList();

const handleClickButton = (data: ButtonsCallBackParams) => {
  console.log(data);
  if (data.buttonRow.code === "edit") {
    handleOpen();
  } else if (data.buttonRow.code === "view") {
    return;
  } else if (data.buttonRow.code === "delete") {
    console.log("删除", data);
    show.value = true;
  }
};
const handleSelectionChange = (val: TableRow[]) => {
  multipleSelection.value = val;
};
const handlePaginationChange = (_pageInfo: PageInfo): void => {
  pageInfo.value = _pageInfo;

  getList();
};
// end table

// start 表单弹窗
const rules = {
  name: [
    {
      required: true,
      message: "请输入名称",
    },
  ],
  tag: [
    {
      required: true,
      message: "请输入标签",
    },
  ],
};

const columns: PlusColumn[] = [
  {
    label: "组织名称",
    width: 120,
    prop: "name",
    valueType: "copy",
    colProps: {
      span: 12,
    },
  },
  {
    label: "组织级别",
    width: 120,
    prop: "status",
    valueType: "select",
    colProps: {
      span: 12,
    },
    options: [
      {
        label: "中国",
        value: "0",
        color: "red",
      },
      {
        label: "美国",
        value: "1",
        color: "blue",
      },
      {
        label: "意大利",
        value: "2",
        color: "yellow",
      },
      {
        label: "英国",
        value: "3",
        color: "red",
      },
    ],
  },
  {
    label: "上级组织",
    prop: "city",
    valueType: "cascader",
    colProps: {
      span: 12,
    },
    options: [
      {
        value: "0",
        label: "陕西",
        children: [
          {
            value: "0-0",
            label: "西安",
            children: [
              {
                value: "0-0-0",
                label: "新城区",
              },
              {
                value: "0-0-1",
                label: "高新区",
              },
              {
                value: "0-0-2",
                label: "灞桥区",
              },
            ],
          },
        ],
      },
      {
        value: "1",
        label: "山西",
        children: [
          {
            value: "1-0",
            label: "太原",
            children: [
              {
                value: "1-0-0",
                label: "小店区",
              },
              {
                value: "1-0-1",
                label: "古交市",
              },
              {
                value: "1-0-2",
                label: "万柏林区",
              },
            ],
          },
        ],
      },
    ],
  },
  {
    label: "组织层级",
    prop: "city",
    valueType: "cascader",
    colProps: {
      span: 12,
    },
    options: [
      {
        value: "0",
        label: "陕西",
        children: [
          {
            value: "0-0",
            label: "西安",
            children: [
              {
                value: "0-0-0",
                label: "新城区",
              },
              {
                value: "0-0-1",
                label: "高新区",
              },
              {
                value: "0-0-2",
                label: "灞桥区",
              },
            ],
          },
        ],
      },
      {
        value: "1",
        label: "山西",
        children: [
          {
            value: "1-0",
            label: "太原",
            children: [
              {
                value: "1-0-0",
                label: "小店区",
              },
              {
                value: "1-0-1",
                label: "古交市",
              },
              {
                value: "1-0-2",
                label: "万柏林区",
              },
            ],
          },
        ],
      },
    ],
  },
  {
    label: "组织编码",
    width: 120,
    prop: "name",
    valueType: "copy",
    colProps: {
      span: 12,
    },
  },
  {
    label: "公司全称",
    width: 120,
    prop: "status",
    valueType: "select",
    colProps: {
      span: 12,
    },
    options: [
      {
        label: "中国",
        value: "0",
        color: "red",
      },
      {
        label: "美国",
        value: "1",
        color: "blue",
      },
      {
        label: "意大利",
        value: "2",
        color: "yellow",
      },
      {
        label: "英国",
        value: "3",
        color: "red",
      },
    ],
  },
  {
    label: "编制人数",
    width: 120,
    prop: "name",
    valueType: "copy",
    colProps: {
      span: 12,
    },
  },
  {
    label: "在编人数",
    width: 120,
    prop: "name",
    valueType: "copy",
    colProps: {
      span: 12,
    },
  },
  {
    label: "部门负责人",
    width: 120,
    prop: "name",
    valueType: "copy",
    colProps: {
      span: 12,
    },
  },
  {
    label: "上级负责人",
    width: 120,
    prop: "name",
    valueType: "copy",
    colProps: {
      span: 12,
    },
  },
  {
    label: "组织描述",
    prop: "desc",
    valueType: "textarea",
    fieldProps: {
      maxlength: 10,
      showWordLimit: true,
      autosize: { minRows: 2, maxRows: 4 },
    },
  },
  {
    label: "备注",
    prop: "desc",
    valueType: "textarea",
    fieldProps: {
      maxlength: 10,
      showWordLimit: true,
      autosize: { minRows: 2, maxRows: 4 },
    },
  },
  {
    label: "设立时间",
    prop: "time",
    valueType: "date-picker",
    colProps: {
      span: 12,
    },
  },
];

const confirmLoading = ref(false);
const visible = ref(false);
const values = ref<FieldValues>({ name: "名称" });

const handleOpen = () => {
  visible.value = true;
};
const handleSubmit = () => {
  confirmLoading.value = true;
  setTimeout(() => {
    confirmLoading.value = false;
    visible.value = false;
  }, 2000);
};
const handleCancel = () => {
  visible.value = false;
};

const dropdownItemClick = (type: string) => {
  console.log(type);
  if (type === "copy") {
    console.log("复制");
    show.value = true;
  } else if (type === "printer") {
    console.log("打印");
  } else if (type === "export") {
    console.log("导出");
  } else if (type === "archive") {
    console.log("归档");
  }
};
// end 表单弹窗

// start 确认弹窗
const show = ref(false);

const handleSmallConfirm = () => {
  ElMessage.success("删除成功");
  show.value = false;
};
const handleSmallCancel = () => {
  show.value = false;
};
// end 确认弹窗

// start tree

interface Tree {
  id: number;
  label: string;
  children?: Tree[];
}
const filterText = ref("");
const treeRef = ref<TreeInstance>();
// let id = 1000;

const append = (data: Tree) => {
  visible.value = true;
  console.log(data);
  return;
  // const newChild = { id: id++, label: "testtest", children: [] };
  // if (!data.children) {
  //   data.children = [];
  // }
  // data.children.push(newChild);
  // dataSource.value = [...dataSource.value];
};

const remove = (node: Node, data: Tree) => {
  console.log(node, data);
  show.value = true;
  // const parent = node.parent;
  // const children: Tree[] = parent.data.children || parent.data;
  // const index = children.findIndex((d) => d.id === data.id);
  // children.splice(index, 1);
  // dataSource.value = [...dataSource.value];
};

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};

const dataSource = ref<Tree[]>([
  {
    id: 1,
    label: "集团总部",
    children: [
      {
        id: 4,
        label: "深邦智能科技",
        children: [
          {
            id: 2,
            label: "总经办",
          },
          {
            id: 3,
            label: "人力资源中心",
          },
          {
            id: 31,
            label: "市场中心",
          },
          {
            id: 31,
            label: "产品研发中心",
            children: [
              {
                id: 71,
                label: "产品中心",
              },
              {
                id: 81,
                label: "研发中心",
              },
            ],
          },
          {
            id: 91,
            label: "行政中心",
          },
          {
            id: 101,
            label: "销售中心",
          },
        ],
      },
      {
        id: 42,
        label: "广东深邦科技",
        children: [
          {
            id: 22,
            label: "产品研发中心",
            children: [
              {
                id: 52,
                label: "产品中心",
              },
              {
                id: 62,
                label: "研发中心",
              },
            ],
          },
          {
            id: 91,
            label: "行政中心",
          },
          {
            id: 101,
            label: "市场中心",
          },
        ],
      },
      {
        id: 421,
        label: "深邦智慧城市科技",
        children: [
          {
            id: 221,
            label: "产品研发中心",
            children: [
              {
                id: 521,
                label: "产品中心",
              },
              {
                id: 621,
                label: "研发中心",
              },
            ],
          },
          {
            id: 911,
            label: "行政中心",
          },
          {
            id: 1011,
            label: "市场中心",
          },
        ],
      },
    ],
  },
]);
</script>
